<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!-- 引入 layui.css -->
    <link href="//unpkg.com/layui@2.8.0/dist/css/layui.css" rel="stylesheet">
    <!-- 引入 layui.js -->
    <script src="//unpkg.com/layui@2.8.0/dist/layui.js"></script>
    <style>
        #layuiTop{
            margin-top: -360px;
            margin-left: 250px;
        }
        .layui-collapse{
            margin-left: 500px;
        }
        .layui-table-view layui-table-view-1 layui-form layui-border-box{
            height: 0px;
        }

    </style>
</head>
<body onload="generateOrderNumber()">
<input type="hidden" id="clientId" name="clientId">
<form enctype="multipart/form-data">
    <div class="layui-form" action="form.html">
        <div class="layui-form-item">
            <label class="layui-form-label">订单编号</label>
            <div class="layui-input-block">
                <input type="text" style="width: 190px"  id="quotationNumber" name="quotationNumber" lay-verify="required" placeholder="订单编号(请不要含有特殊字符/、?等)"
                       autocomplete="off" class="layui-input" readonly>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" >公司名称</label>
                <div class="layui-input-inline">
                    <select lay-filter="clientName"   id="clientName"  name="clientName" lay-verify="required" lay-search>
                        <option value="-1" id="pp">请选择</option>
                    </select>
                </div>
            </div>
        </div>
        <%--<div class="layui-div">--%>
        <%--<table class="layui-hide" id="dataTable" lay-filter="dataTable" style="width: 400px ;height: 200px"></table>--%>
        <%--</div>--%>
        <div class="layui-form-item">
            <label class="layui-form-label">交期时间</label>
            <div class="layui-input-block">
                <input type="date" id="deliveryTime" name="deliveryTime"class="layui-input" style="width: 200px" lay-verify="required" placeholder="交期时间" autocomplete="off"
                >
            </div>
        </div>
        <div class="layui-form-item">
            <%-- <div class="layui-inline">
                 <label class="layui-form-label">订单数量</label>
                 <div class="layui-input-block">
                     <input type="text" style="width: 190px"  name="orderQuantity" lay-verify="required" placeholder="0" autocomplete="off"
                            class="layui-input">
                 </div>
             </div>--%>
            <div class="layui-form-item">
                <label class="layui-form-label">订单金额</label>
                <div class="layui-input-block">
                    <input type="text" style="width: 190px" readonly="true" id="orderMoney" name="orderMoney" lay-verify="required" placeholder="订单金额" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">交货地址</label>
                <div class="layui-input-block">
                    <input type="text" style="width: 500px" id="deliveryAddress" name="deliveryAddress" lay-verify="required" placeholder="交货地址" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注描述</label>
                <div class="layui-input-block">
                    <input type="text"style="width: 500px" id="orderSrc" name="orderSrc" lay-verify="required" placeholder="备注" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>
    </div>
</form>
<div class="layui-inline">
    <label class="layui-form-label">联系人</label>
    <div class="layui-input-inline">
        <input type="text" id="contactName"name="contactName" lay-verify="required" placeholder="联系人"
               autocomplete="off" class="layui-input" readonly="true">
    </div>
</div>
<div class="layui-inline">
    <label class="layui-form-label">联系方式</label>
    <div class="layui-input-inline layui-input-wrap">
        <input type="text" id="contactPhone" name="contactPhone" lay-verify="required" placeholder="联系方式"
               autocomplete="off" class="layui-input" readonly="true">
    </div>
</div>
<div class="layui-container" style="margin-left: 35px">
    <button class="layui-btn" id="showTableBtn">选择款号</button>
    <table class="layui-hide" id="dataTable" lay-filter="dataTable"></table>
</div>
<div class="layui-form-item" style="margin-top: 60px">
    <div class="layui-input-block">
        <button type="submit" class="layui-btn" lay-submit lay-filter="demo1">返回列表</button>
        <button  class="layui-btn layui-btn-primary" onclick="add()">保存</button>
    </div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
    layui.use(['table', 'form'],function () {
        var table = layui.table;
        var form = layui.form;
        $('#showTableBtn').click(function () {
            table.render({
                elem: '#dataTable',
                height: 600,
                url: 'orderFrom/getStyleNumberList',
                page: true,
                limit: 8,
                limits: [4, 8, 12],
                toolbar: '#toolbar',
                cols: [
                    [
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'styleNumberId', title: '款号ID', width: 100, sort: true, fixed: 'left' },
                        { field: 'styleNumber', title: '款号', width: 100 },
                        { field: 'brand', title: '品牌', width: 100 },
                        { field: 'styleName', title: '款式名称 ', width: 100 },
                       // { field: 'styleNumberImg', title: '品牌', width: 100 }
                    ],
                ],
                done: function(res, curr, count) {
                    // 表格渲染完成后的回调函数
                    // 添加选择事件监听
                    table.on('checkbox(dataTable)', function(obj) {
                        // 获取选中的行数据
                        var selectedData = table.checkStatus('dataTable').data;
                        var ids = [];
                        var styleNumberIds = [];
                        for (var i = 0; i < selectedData.length; i++) {
                            ids.push(selectedData[i].styleNumberId);
                            styleNumberIds[i] = selectedData[i].styleNumber;
                        }
                        getStyleNumberList(ids)
                        console.log(styleNumberIds)
                        //发送AJAX请求，获取报价列gte表
                        $.ajax({
                            url: 'orderFrom/getQuotationList',
                            type: 'post',
                            data: JSON.stringify(styleNumberIds),
                            dataType: 'json',
                           contentType:"application/json;charset=utf-8",
                            success: function (data) {
                                if (data.length > 0) {
                                    var totalAmount = 0;
                                    for (var i = 0; i < data.length; i++) {
                                        var styleNumber = data[i].styleNumber;
                                        var fullAmount = (data[i].costWithTax)*2;

                                        if (styleNumberIds.hasOwnProperty(styleNumber)) {
                                            styleNumberIds[styleNumber] += parseFloat(fullAmount);
                                        } else {
                                            styleNumberIds[styleNumber] = parseFloat(fullAmount);
                                        }

                                        totalAmount += parseFloat(fullAmount);
                                    }
                                    $('#orderMoney').val(totalAmount);
                                    //alert("有数据");
                                } else {
                                   // console.log("没有数据");
                                    alert("当前款号没有核价单价格");
                                }
                            },
                            error: function () {
                                console.log('请求失败');
                            }
                        });
                    });


                }
            });
        })
    });
    // 监听复选框选择状态
    // table.on('checkbox(demo)', function (obj) {
    //     var selectedData = table.checkStatus('demo').data;
    //     var selectedIds = [];
    //     for (var i = 0; i < selectedData.length; i++) {
    //         selectedIds.push(selectedData[i].styleNumberId);
    //     }
    //     console.log(selectedIds);
    // });
</script>
<script>
    var abc = [];
    function getStyleNumberList(ids) {
        abc=ids
    }
    //订单录入
    function add() {
        alert(abc)//款号id数组
        //点击保存进行判空保留填写的数据
        event.preventDefault();
        let quotationNumber = $('[name=quotationNumber]').val()
        let clientName = $('[name=clientName]').val()
        let deliveryTime = $('[name=deliveryTime]').val()
        let orderMoney = $('[name=orderMoney]').val()
        let deliveryAddress = $('[name=deliveryAddress]').val()
        let orderSrc = $('[name=orderSrc]').val()
        let clientId = $('[name=clientId]').val();
        alert(clientId)
        if(clientName==-1){
            alert("请选择公司名称")
            return false;
        }
        if (isNullOrEmpty(quotationNumber)){
            alert("请填写订单编号")
            return false
        }
        if (isNullOrEmpty(deliveryTime)){
            alert('请选择交期时间')
            return false
        }
        let orderMoneyList=/^[^\d]+$/;
        if(isNullOrEmpty(orderMoney)){
            alert("请填写订单金额")
            return false
        }else {
            if(orderMoneyList.test(orderMoney)){
                alert("订单金额不可以为字符")
                return false
            }
            else if(orderMoney>9999999){
                alert("订单金额不可以超7位数")
                return false
            } else if (orderMoney === "0") {
                alert("订单金额不可以为零");
                return false;
            }
        }
        if (isNullOrEmpty(deliveryAddress)){
            alert("请填写交货地址")
            return false
        }
        if (isNullOrEmpty(orderSrc)){
            alert("请填写备注")
            return false
        }
        let a= getStyleNumberList(abc);
        let data ={};
        let value = $('form').serializeArray();
        $.each(value, function (index,item) {
            data[item.name] = item.value;
        });
        alert(a)
        id= data['clientId']
        data['listId'] = abc;//把那到的款号id数组放到实体类里面在在controller做
        let OrderFrom = JSON.stringify(data);
        $.ajax( {
            "url"            :  "orderFrom/add",                      // 要提交的URL路径
            "type"         :  "post",                     // 发送请求的方式
            "data": OrderFrom,                    // 要发送到服务器的数据
            "dataType" :  "json",                   // 期望接受的数据格式
            "contentType":"application/json;charset=utf-8;",
            "success"  :  function(result) {  // 请求成功后要执行的代码
                // console.log(result);
                if(result.success==200){
                    alert("添加成功");
                      window.location.href="tosearch";
                    // clearInputs();
                    generateOrderNumber();
                }else{
                    alert("新增失败");
                }
            },
            "error"       :  function() {           // 请求失败后要执行的代码
                alert("出错了")
            }
        } );

    }
//     function add() {
//         alert(abc)//款号id数组
//
//         //点击保存进行判空保留填写的数据
//         event.preventDefault();
//         let quotationNumber = $('[name=quotationNumber]').val()
//         let clientName = $('[name=clientName]').val()
//         let deliveryTime = $('[name=deliveryTime]').val()
//         let orderMoney = $('[name=orderMoney]').val()
//         let deliveryAddress = $('[name=deliveryAddress]').val()
//         let orderSrc = $('[name=orderSrc]').val()
//         let clientId = $('[name=clientId]').val();
// alert(clientName)
//         alert(clientId)
//         if(clientName==-1){
//             alert("请选择公司名称")
//             return false;
//         }
//         if (isNullOrEmpty(quotationNumber)){
//             alert("请填写订单编号")
//             return false
//         }
//         if (isNullOrEmpty(deliveryTime)){
//             alert('请选择交期时间')
//             return false
//         }
//         let orderMoneyList=/^[^\d]+$/;
//         if(isNullOrEmpty(orderMoney)){
//             alert("请填写订单金额")
//             return false
//         }else {
//             if(orderMoneyList.test(orderMoney)){
//                 alert("订单金额不可以为字符")
//                 return false
//             }else if(orderMoney>9999999){
//                 alert("订单金额不可以超7位数")
//                 return false
//             }
//         }
//         if (isNullOrEmpty(deliveryAddress)){
//             alert("请填写交货地址")
//             return false
//         }
//         if (isNullOrEmpty(orderSrc)){
//             alert("请填写备注")
//             return false
//         }
//         let a= getStyleNumberList(abc);
//         let data ={};
//         let value = $('form').serializeArray();
//         $.each(value, function (index,item) {
//             data[item.name] = item.value;
//         });
//         id= data['clientId']
//         alert(id)
//         data['listId'] = abc;//把那到的款号id数组放到实体类里面在在controller做
//         let OrderFrom = JSON.stringify(data);
//         $.ajax( {
//             "url"            :  "orderFrom/add",                      // 要提交的URL路径
//             "type"         :  "post",                     // 发送请求的方式
//             "data": OrderFrom,                    // 要发送到服务器的数据
//             "dataType" :  "json",                   // 期望接受的数据格式
//             "contentType":"application/json;charset=utf-8;",
//             "success"  :  function(result) {  // 请求成功后要执行的代码
//                  console.log(result);
//                 if (result.success == 200) {
//                     alert("添加成功");
//                     window.location.href = "tosearch";
//                     generateOrderNumber();
//                 } else {
//                     alert("新增失败");
//                 }
//             },
//             "error"       :  function() {           // 请求失败后要执行的代码
//                 alert("出错了")
//             }
//         } );
//
//     }
    function isNullOrEmpty(str) {
        if (str == null || str==""){
            return true
        }else {
            return false
        }
    }
</script>
<script>
    //公司名称联系人联系电话的三级联动
    layui.use(['form'], function() {
        var form = layui.form;

        // 监听下拉框选中事件
        form.on('select(clientName)', function(data) {
            var selectedValue = data.value;
            console.log(selectedValue);
            // 设置隐藏的input框的值为选中的ID值
            document.getElementById('clientId').value = selectedValue;
            // document.getElementById('styleNumberList').value = selectedValue;

            // 发送请求，查询相关数据
            $.ajax({
                url: 'orderFrom/getClientIdList',
                type: 'GET',
                data: {clientId: selectedValue},
                dataType: 'json',
                success: function(data) {
                    console.log(data)
                    // 将查询结果显示在输入框中
                    // $('#contactName').val(data.contactName);
                    // 遍历数组，获取每个元素的contactName值
                    if(data==-1){
                        document.getElementById("contactName").value = '';
                        document.getElementById("contactPhone").value = '';
                    }else {
                        for (var i = 0; i < data.length; i++) {
                            var contactName = data[i].contactName;
                            var contactPhone = data[i].contactPhone;
                            console.log(contactName);
                            // 将contactName值显示在输入框中
                            $('#contactName').val(contactName);
                            $('#contactPhone').val(contactPhone);
                        }
                    }

                },
                error:function () {
                    alert("没有改联系人")
                }
            });
        });
        // 从后端接口获取数据
        $.ajax({
            url: 'orderFrom/getClientClientId',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                var dropdown = document.getElementById('clientName');

                // 渲染下拉框选项
                data.forEach(function(item) {
                    var option = document.createElement('option');
                    option.value = item.clientId;
                    option.text = item.clientName;
                    dropdown.appendChild(option);
                });

                // 重新渲染表单元素
                form.render('select');
            }
        });
    });
</script>
<script>
    //生成随机数订单编号
    function generateOrderNumber() {
        // 生成五位数的随机数
        var randomNum = Math.floor(Math.random() * 90000) + 10000;

        // 获取当前时间戳
        var timestamp = new Date().getTime();

        // 将时间戳和随机数相加得到订单编号
        var orderNumber = timestamp + randomNum;

        // 将订单编号设置为输入框的值
        document.getElementById("quotationNumber").value = orderNumber;
        // document.getElementById("orderId").value = orderNumber;



    }
    //渲染款号下拉框
    layui.use(['form'], function() {
        var form = layui.form;

        // 监听下拉框选中事件
        form.on('select(styleNumber)', function(data) {
            var selectedValue = data.value;
            console.log(selectedValue);
        });
        // 从后端接口获取数据
        $.ajax({
            url: 'orderFrom/getStyleNumber',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                var dropdown = document.getElementById('styleNumber');

                // 渲染下拉框选项
                data.forEach(function(item) {
                    var option = document.createElement('option');

                    option.value = item.styleNumber;
                    option.text = item.styleNumber; // 设置选项的显示文本，可以根据需求调整

                    //  dropdown.appendChild(option);
                });
                // 重新渲染表单元素
                form.render('select');
            }
        });
    });
</script>
<script>
    // layui.use('table', function () {
    //     var table = layui.table;
    //
    //     // 监听表格事件
    //     table.on('checkbox(dataTable)', function(obj) {
    //         // 获取选中的行数据
    //         var selectedData = table.checkStatus('dataTable').data;
    //         var ids = [];
    //         for (var i = 0; i < selectedData.length; i++) {
    //             ids.push(selectedData[i].styleNumberId);
    //         }
    //         // 打印选中的行数据
    //         getStyleNumberList(ids)
    //         alert(ids);
    //     });
    // });
</script>
</html>
